//
//  PicManageVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/16.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "PicManageVC.h"
#import "UploadPicVC.h"
#import "PicListModel.h"
#import "PicPageListModel.h"

@interface PicManageVC () <UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong) UICollectionView *collectView;
@property (nonatomic,strong) UIButton *confirmBtn;
@property (nonatomic,assign) BOOL isCtrPic;

@end

@implementation PicManageVC

@synthesize picArr = _picArr;

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];

    //添加图片页面,pop出来后,必须请求数据
    if (_isChange) {
        [self getDataWithPage:@"1" pageSize:@"50"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Config UI
- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    if (_isChange || _isSubmit)
    {
        self.title = @"照片管理";
        [self createManageBtnAddBtn];
    }
    else
    {
        self.title = @"照片查看";
    }

    //每行图片数
    NSInteger imgNum = 4;

    //间隔
    CGFloat imgSpace = 3.0;

    //图片宽度
    CGFloat imgWid = (SCREEN_WIDTH - (imgNum+1)*imgSpace)/imgNum;

    UICollectionViewFlowLayout *collectLayout = [[UICollectionViewFlowLayout alloc] init];
    // 定义大小
    collectLayout.itemSize = CGSizeMake(imgWid, imgWid);
    // 设置最小行间距
    collectLayout.minimumLineSpacing = imgSpace;
    // 设置垂直间距
    collectLayout.minimumInteritemSpacing = imgSpace;

    _collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:collectLayout];
    _collectView.backgroundColor = [UIColor whiteColor];
    _collectView.dataSource = self;
    _collectView.delegate = self;
    [self.view addSubview:_collectView];
    [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@3);
        make.left.equalTo(@3);
        make.right.equalTo(@-3);
        make.bottom.equalTo(@-65);
    }];

    [_collectView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

}

- (void)createManageBtnAddBtn
{
    [self createRightButton:@"管理" selector:@selector(ctrPic)];

    //创建底部按钮
    _confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_confirmBtn setBackgroundColor:KwBlueColor];
    [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_confirmBtn setTitle:@"添加照片" forState:UIControlStateNormal];
    _confirmBtn.titleLabel.font = KwFont(16.0);
    [_confirmBtn addTarget:self action:@selector(bottomBtnAction) forControlEvents:UIControlEventTouchUpInside];
    _confirmBtn.layer.masksToBounds = YES;
    _confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:_confirmBtn];
    [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-20);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
        make.height.equalTo(@35);
    }];

}

#pragma mark - Load data


#pragma mark - Data request
- (void)getDataWithPage:(NSString *)page pageSize:(NSString *)pageSize
{
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
    [picRequest startRequestQueryPicWithProcessId:_orderId pageNo:page pageSize:pageSize type:[NSString stringWithFormat:@"%zd", _picType]];
    [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            //当前显示的数据
            if(!self.picArr)
            {
                self.picArr = [NSMutableArray array];
            }
            PicPageListModel *pageModel = [[PicPageListModel alloc] initWithDictionary:result[@"pageList"] error:nil];
            if ([pageModel.count integerValue] > 0)
            {
                self.picArr = pageModel.list.mutableCopy;
            }
            if (_collectView)
            {
                [_collectView reloadData];
            }

        }
    }];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.picArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *urlStr;
    PicListModel *model = self.picArr[indexPath.item];
    if (model.imgs)
    {
        urlStr = model.imgs;
    }
    else
    {
        urlStr = @"";
    }
    NSURL *imgurl = [NSURL URLWithString:urlStr];
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    UIImageView *imgView = [UIImageView new];
    imgView.backgroundColor = [UIColor blackColor];
    [imgView sd_setImageWithURL:imgurl placeholderImage:nil];
    [cell addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(@0);
    }];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.tag = 100+indexPath.row;
    [btn setImage:kImg(@"delete") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(deletePicWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(@0);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];

    if (_isCtrPic == YES)
    {
        //管理照片
        btn.hidden = NO;
        btn.enabled = YES;
    }
    else
    {
        btn.hidden = YES;
        btn.enabled = NO;
    }

    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 点击高亮
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
//    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
//    cell.backgroundColor = [UIColor greenColor];
}


// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicListModel *model = self.picArr[indexPath.item];
    [[KwBigImgView shareInstance] showBigImageWithTitle:model.title?:@"" imageStr:model.imgs];
}

#pragma mark - event response
//管理图片
- (void)ctrPic
{
    [self changeStatus];
    [_collectView reloadData];

}

- (void)onTapLeftBarButton {
    if (self.pictureCallback && (_isChange || _isSubmit)) {
        self.pictureCallback(self.picArr);
    }
//    [super leftBtClickMethod:sender];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)bottomBtnAction
{
    if (_isCtrPic == YES)
    {
        //完成删除
        [self changeStatus];
    }
    else
    {
        UploadPicVC *vc = [[UploadPicVC alloc] init];
        vc.orderId = _orderId;
        vc.isSubmit = self.isSubmit;
        vc.picType = _picType;
        __weak typeof(self) weakSelf = self;
        vc.chooseComplete = ^(NSArray<NSDictionary *> *picData) {
            [picData enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                PicListModel *model = [PicListModel new];
                model.imgs = obj[@"imgs"];
                model.title = obj[@"title"];
                [self.picArr addObject:model];
            }];
            [weakSelf.collectView reloadData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }

}

//删除按钮
- (void)deletePicWithBtn:(UIButton *)btn
{
    NSInteger tag = btn.tag-100;
    PicListModel *model = self.picArr[tag];

    if (self.isSubmit) {
        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        [self.picArr removeObjectAtIndex:tag];
        [_collectView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:tag inSection:0]]];
        return;
    }
    
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
    [picRequest startRequestDeleteOnePicWithImgs:model.imgs];
    [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [self.picArr removeObjectAtIndex:tag];
            [_collectView reloadData];
        }
    }];
}

#pragma mark - private method
//执行状态改变
- (void)changeStatus
{
    if (_isCtrPic == NO)
    {
        //导航改变
        self.navigationItem.rightBarButtonItem.title = @"取消";

        //底部按钮改变
        [_confirmBtn setTitle:@"完成" forState:UIControlStateNormal];

        _isCtrPic = YES;
    }
    else
    {
        //导航改变
        self.navigationItem.rightBarButtonItem.title = @"管理";

        //底部按钮改变
        [_confirmBtn setTitle:@"添加照片" forState:UIControlStateNormal];

        _isCtrPic = NO;
    }
    [self.collectView reloadData];
}
#pragma mark - getter and setter
- (NSMutableArray<PicListModel *> *)picArr {
    if (!_picArr) {
        _picArr = [NSMutableArray array];
    }
    return _picArr;
}

- (void)setPicArr:(NSMutableArray<PicListModel *> *)picArr {
    _picArr = [picArr mutableCopy];
}

@end
